package com.openapi.server.codec;

import com.openapi.config.JT808ServerConfig;
import com.openapi.data.JT808PushData;
import com.openapi.data.Session;
import com.openapi.data.SessionType;
import exsun.jt808.data.util.executorsThread.FixedThreadHandleRunnable;
import com.openapi.service.SessionManager;
import com.openapi.service.SessionManagerFactory;
import exsun.jt808.data.base.JT808Category;
import exsun.jt808.data.config.jt808.Jt808DistributeMsgTopic;
import exsun.jt808.data.http.RawDataDistribute;
import exsun.jt808.data.http.ReqDistribute;
import exsun.jt808.data.util.GsonUtils;
import exsun.jt808.data.util.parse.BitOperator;
import exsun.jt808.data.util.parse.HexStrUtil;
import exsun.jt808.data.util.parse.PackageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
@SuppressWarnings("unused")
public class MsgEncoder extends MessageToByteEncoder<JT808PushData> {

	private static final Logger logger = LoggerFactory.getLogger(MsgDecoder.class);

	private static JT808ServerConfig jt808ServerConfig;
	@Autowired
	public void setJt808ServerConfig(JT808ServerConfig jt808ServerConfig) {
		MsgEncoder.jt808ServerConfig = jt808ServerConfig;
	}

	@Override
	protected void encode(ChannelHandlerContext channelHandlerContext, JT808PushData jt808PushData, ByteBuf byteBuf) throws Exception
	{
		byte[] dataBuffers = buildDataBuffers(jt808PushData);

//		if(jt808PushData.getJt808Category() == JT808Category.platformProactive
//				&&jt808PushData.object.distributeMsgTopic != Jt808DistributeMsgTopic.AlarmAttachmentUpload_Send
//				&&!jt808ServerConfig.getHttpRequestUrl().equals("")
////		        &&isStrExist(jt808PushData.getObject().devNo) == true
//		){
//			//下发指令暂时改为通过调.net接口
//			httpPost(dataBuffers);
//			return;
//		}

		if(channelHandlerContext.channel().isActive()){
			byteBuf.writeBytes(dataBuffers);
			logger.info("send:{}", ByteBufUtil.hexDump(dataBuffers));
		}else {
			logger.info("连接已断开，不推送数据,{},{}",jt808PushData.getObject().devNo, jt808PushData.getObject().msgId);
			return;
		}
	}

	private byte[] buildDataBuffers(JT808PushData jt808PushData){
		byte[] body = jt808PushData.getBody();
		byte[] bs = new byte[0];

		//根据设备号长度或者版本号判断
		int version =jt808PushData.getObject().versionId == null?0:jt808PushData.getObject().versionId;
		if(jt808PushData.getObject().devNo.length() == 20 && version == 0){
			version = 1;
		}

		int property = 0;
		if (version == 0){
			property = body.length;
			bs = BitOperator.concatAll(
					BitOperator.integerTo2Bytes(jt808PushData.getObject().msgId),
					BitOperator.integerTo2Bytes(property),
					HexStrUtil.decodeHex(jt808PushData.getObject().devNo)
			);
		}else{
			property = body.length|0x4000;
			bs = BitOperator.concatAll(
					BitOperator.integerTo2Bytes(jt808PushData.getObject().msgId),
					BitOperator.integerTo2Bytes(property),
					BitOperator.integerTo1Bytes(version),
					HexStrUtil.decodeHex(jt808PushData.getObject().devNo)
			);
		}



//		bs = BitOperator.concatAll(
//				BitOperator.integerTo2Bytes(jt808PushData.getObject().msgId),
//				BitOperator.integerTo2Bytes(body.length),
//				HexStrUtil.decodeHex(jt808PushData.getObject().devNo),
//				BitOperator.integerTo2Bytes(getFlowId(jt808PushData.getObject().devNo,0)),
//				body
//		);

		int serialNo = jt808PushData.getObject().serialNo == 0?
				getFlowId(jt808PushData.getObject().devNo,0):
				jt808PushData.getObject().serialNo;

		byte[] serNo = BitOperator.integerTo2Bytes(serialNo);

		bs = BitOperator.concatAll(bs, serNo, body);
		bs = BitOperator.concatAll(bs,
				BitOperator.integerTo1Bytes(PackageUtil.buildValidateCrc(bs)));
		byte[] separator = new byte[]{ 0x7e };
		return BitOperator.concatAll(
				separator,
				PackageUtil.buildTransferredRequest(bs),
				separator);
	}

	private int getFlowId(String terminalPhone, int defaultValue) {
		SessionManager sessionManager = SessionManagerFactory.GetSessionManager(SessionType.JT_808);
		Session session = sessionManager.findByTerminalPhone(terminalPhone);
		if (session == null) {
			return defaultValue;
		}
		return session.currentFlowId();
	}

	public void httpPost(byte[] dataBuffers){

		RawDataDistribute rawDataDistribute = new RawDataDistribute();
//		rawDataDistribute.Data = dataBuffers;
		rawDataDistribute.subContent = HexStrUtil.bytesToHexStr(dataBuffers);
		rawDataDistribute.PhoneNum = HexStrUtil.encodeHex(dataBuffers,5,6);
		rawDataDistribute.UserId = "java";
		rawDataDistribute.UserName = "java";

		ReqDistribute reqDistribute = new ReqDistribute();
		reqDistribute.DistributeType = "tg_RawDataDistribute";
		reqDistribute.DistributeContent = GsonUtils.getJsonFromObject(rawDataDistribute);
		reqDistribute.DistributeName = "java指令原始数据";

		String json= GsonUtils.getJsonFromObject(reqDistribute);
		String url = jt808ServerConfig.getHttpRequestUrl() +"Publish";
		post(url,json);
	}
	public static void post(String requrl, String json) {
		FixedThreadHandleRunnable.post(requrl, json);
	}
	public static boolean isStrExist(String str) throws IOException {
		File f = new File(System.getProperty("user.dir")+"/DevConfig.txt");
		//字节流到字符流
		InputStreamReader read = new InputStreamReader(new FileInputStream(f), "UTF-8"); //编码格式
		//字符输入流中读取文本并缓冲字符
		BufferedReader bufferedReader = new BufferedReader(read);
		String line = null;
		while ((line = bufferedReader.readLine()) != null) {
			if (line.contains(str)) {
				return true;
			}
		}
		bufferedReader.close();
		return false;
	}
}
